import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:gluz/app/common/extension/app_extension.dart';
export 'package:gluz/app/common/extension/app_extension.dart';
import 'package:gluz/app/common/native_bridge.dart';
import 'package:gluz/app/data/user_profile_entity.dart';
import 'package:gluz/app/utils/app_env.dart';
import 'package:gluz/app/utils/http_util.dart';
import 'package:gluz/app_translation.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:logger/logger.dart' as log;
import 'app/routes/app_pages.dart';
import 'app/utils/toast_util.dart';
import 'package:dartx/dartx.dart';

final log.Logger logger = log.Logger(
  printer: log.PrettyPrinter(
    methodCount: 4, // Number of method calls to be displayed
    errorMethodCount: 8, // Number of method calls if stacktrace is provided
    lineLength: 120, // Width of the output
    colors: true, // Colorful log messages
    printEmojis: true, // Print an emoji for each log message
    printTime: false, // Should each log print contain a timestamp
  ),
);


Future<void> initServices() async {
  logger.i('starting services ...');
  WidgetsFlutterBinding.ensureInitialized();
  await app.initOtherServices();
  logger.i('All services started...');
}

final app = AppSession();

class AppSession {
  /// 网络环境
  final Connectivity connectivity = Connectivity();
  late StreamSubscription<List<ConnectivityResult>> _connectivitySubscription;
  List<ConnectivityResult> connectionStatus = [ConnectivityResult.none];

  /// 是否有网
  var isNetworkOK = true.obs;
  /// 是否是蜂窝网络
  var isCellularNet = false.obs;
  /// http 请求
  late HttpUtil http = HttpUtil();
  /// 存储
  late GetStorage storage = GetStorage();
  /// 软件包信息
  late PackageInfo packageInfo;

  late APPEnv env = APPEnv();

  Future<void> initOtherServices() async {
    env.envType = AppEnvEnum.dev;
    await http.setup();
    await GetStorage.init();
    packageInfo = await PackageInfo.fromPlatform();
    await initConnectivity();
    await NativeBridge.initialize();
    fetchAllDictionaryList();

    // getShopCategory(useCache: false);
  }

  Future<void> initConnectivity() async {
    late List<ConnectivityResult> result;
    try {
      result = await connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      logger.e('Couldn\'t check connectivity status', error: e);
      return;
    }
    _connectivitySubscription =
        connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
    return _updateConnectionStatus(result);
  }

  Future<void> _updateConnectionStatus(List<ConnectivityResult> result) async {
    isNetworkOK.value = !result.contains(ConnectivityResult.none);
    isCellularNet.value = result.contains(ConnectivityResult.mobile);
    if (isNetworkOK.value == false) {
      ToastUtil.show('当前无网络,请检查网络连接'.tr);
    } else if (isCellularNet.isTrue) {
      // ToastUtil.show('当前为手机蜂窝网络,请注意流量消耗');
    }
  }

  /// 当前语言是否是俄文
  bool isLangRU() {
    bool isLangRU = storage.read('isLangRU') ?? false;
    return isLangRU;
  }

  void translationToRU() {
    AppTranslation.translationToRU();
    storage.write('isLangRU', true);
  }

  void translationToCN() {
    AppTranslation.translationToCN();
    storage.write('isLangRU', false);
  }

  void keyboardDismiss() {
    FocusScope.of(Get.context!).requestFocus(FocusNode());
    SystemChannels.textInput.invokeMethod('TextInput.hide');
  }

  /// 是否已登录
  bool isLogin() {
    UserProfileEntity? user = getUser();
    String token = user?.token ?? '';
    return token.isNotEmpty;
  }

  void logout() {
    removeUser();
    Get.deleteAll();
    Get.offNamed(Routes.LOGIN);
  }

  /// token CRUD
  void setToken(String token) {
    storage.write('token', token);
  }
  String? getToken() {
    return storage.read('token');
  }
  void removeToken() {
    storage.remove('token');
  }

  /// User CRUD
  void setUser(UserProfileEntity user) {
    Map<String, dynamic> userMap = user.toJson();
    storage.write('user', userMap);
  }
  UserProfileEntity? getUser() {
    Map<String, dynamic>? userMap = storage.read<Map<String, dynamic>>('user');
    if (userMap == null) return null;
    return UserProfileEntity.fromJson(userMap);
  }
  void removeUser() {
    removeToken();
    storage.remove('user');
  }

}